package pe.edu.upla.lamerced.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.springframework.beans.factory.annotation.Autowired;

import pe.edu.upla.lamerced.bean.Detallefactura;
import pe.edu.upla.lamerced.bean.Detservicios;
import pe.edu.upla.lamerced.bean.Factura;
import pe.edu.upla.lamerced.bean.Hospedaje;
import pe.edu.upla.lamerced.service.HospedajeService;
import pe.edu.upla.lamerced.service.ServiciosService;
import pe.edu.upla.lamerced.utiles.Utiles;

public class ReportesAction extends DispatchAction {

	private static final Logger logger = Logger.getLogger(ReportesAction.class);
	@Autowired
	DataSource dataSource;
	
	@Autowired
	private HospedajeService hospedajeService;
	
	@Autowired
	private ServiciosService serviciosService;
	
	public ActionForward preRepReservas(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		File report = new File(this.getServlet().getServletContext().getRealPath("/reportes/repHospPorReserva.jasper"));
        Map params = new HashMap();
        byte[] b = JasperRunManager.runReportToPdf(report.getPath(), params,dataSource.getConnection());
        response.setContentType("application/pdf");
        response.setContentLength(b.length);
        ServletOutputStream o = response.getOutputStream();
        o.write(b,0,b.length);
        o.flush();
        o.close();
        
		return null;
	}
	
	public ActionForward preRepHospedajes(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		File report = new File(this.getServlet().getServletContext().getRealPath("/reportes/repHospPorHospedaje.jasper"));
        Map params = new HashMap();
        byte[] b = JasperRunManager.runReportToPdf(report.getPath(), params,dataSource.getConnection());
        response.setContentType("application/pdf");
        response.setContentLength(b.length);
        ServletOutputStream o = response.getOutputStream();
        o.write(b,0,b.length);
        o.flush();
        o.close();
        
		return null;
	}
	
	public ActionForward repIngservicios(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		
		File report = new File(this.getServlet().getServletContext().getRealPath("/reportes/repIngServicios.jasper"));
        Map params = new HashMap();
        byte[] b = JasperRunManager.runReportToPdf(report.getPath(), params,dataSource.getConnection());
        response.setContentType("application/pdf");
        response.setContentLength(b.length);
        ServletOutputStream o = response.getOutputStream();
        o.write(b,0,b.length);
        o.flush();
        o.close();
        
		return null;
	}
	public ActionForward repIngHospedaje(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		File report = new File(this.getServlet().getServletContext().getRealPath("/reportes/repIngresosHospedaje.jasper"));
        Map params = new HashMap();
        byte[] b = JasperRunManager.runReportToPdf(report.getPath(), params,dataSource.getConnection());
        response.setContentType("application/pdf");
        response.setContentLength(b.length);
        ServletOutputStream o = response.getOutputStream();
        o.write(b,0,b.length);
        o.flush();
        o.close();
        
		return null;
	}
	
	public ActionForward repOcupacionHotel(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		File report = new File(this.getServlet().getServletContext().getRealPath("/reportes/repOcupacionHotel.jasper"));
        Map params = new HashMap();
        byte[] b = JasperRunManager.runReportToPdf(report.getPath(), params,dataSource.getConnection());
        response.setContentType("application/pdf");
        response.setContentLength(b.length);
        ServletOutputStream o = response.getOutputStream();
        o.write(b,0,b.length);
        o.flush();
        o.close();
        
		return null;
	}
	
	public ActionForward verHospedajePDF(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug(" vista acutal de factura");
            logger.debug(" pre generar factura ");
            String cod = request.getParameter("cod");
            Hospedaje hos =  hospedajeService.obtenerHospedaje(Integer.parseInt(cod));
           	hos.setEstado(3);
           	hos.getHabitacion().setEstado(0);
           	hos.setFecSalida(new Date());
           	
           	Calendar cal = new GregorianCalendar();
           	cal.setTime(hos.getFecAlquiler());
           	
           	Calendar cal2 = new GregorianCalendar();
           	cal2.setTime(hos.getFecSalida());
           	int dias = cal.get(Calendar.DAY_OF_YEAR);
           	int dias2 = cal2.get(Calendar.DAY_OF_YEAR);
           	
           	hos.setDiasreserva(dias2 - dias);
           	
           	logger.debug("d"+ hos.getDiasreserva());
           	List<Detservicios> lis = serviciosService.listarServicioHospedaje(hos.getIdhospedaje());
           	
           	//TODO crear factura y detalle de factura con monto calculado
           	Factura fac = new Factura();
           	fac.setHospedaje(hos);
           	fac.setFecha(new Date());
           	//fac.setDetallefacturas(detallefacturas)
           	Collection<Detallefactura> lisDet = new ArrayList<Detallefactura>();
           	double monto = hos.getHabitacion().getPrecioBase();
           	for(Detservicios det : lis){
           		lisDet.add(new Detallefactura(fac,det, new Long( det.getServicios().getTarifa() *  det.getCantidad() )));
           		monto = monto + (det.getServicios().getTarifa() *  det.getCantidad());
           	}
           	fac.setMontoBruto(monto);
           	fac.setIgv( monto * 0.19 );
           	fac.setMontoNeto( monto + fac.getIgv() );
           	
           	//request.setAttribute("lstServi", lisDet);
           	//request.setAttribute("dfact", fac);
           	
           	JRBeanCollectionDataSource dataSource;
            Map<String, String> pars = new HashMap<String, String>();
          	pars.put("montobruto", fac.getMontoBruto().toString());
          	pars.put("montoneto", fac.getMontoNeto().toString());
          	pars.put("igv", fac.getIgv().toString());
          	pars.put("nombrecliente", fac.getHospedaje().getUsersByIdUsuarioCli().getNombrecompleto());
          	pars.put("fecha",Utiles.dateToString( fac.getHospedaje().getFecAlquiler(), Utiles.FORMATO_FECHA_CORTA));
          	pars.put("habitacion", fac.getHospedaje().getHabitacion().getNumero().toString());
          	pars.put("dias", fac.getHospedaje().getDiasreserva().toString());
   			
   			dataSource = new JRBeanCollectionDataSource(lisDet);          
           	File report = new File(this.getServlet().getServletContext().getRealPath("/reportes/factura.jasper"));           
            byte[] b = JasperRunManager.runReportToPdf(report.getPath(), pars,dataSource);
            response.setContentType("application/pdf");
            response.setContentLength(b.length);
            ServletOutputStream o = response.getOutputStream();
            o.write(b,0,b.length);
            o.flush();
            o.close();
            
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return null;// mapping.findForward("reserva");
		}
		return null;//mapping.findForward("confirmarpago");
	}
}